const { app, BrowserWindow, screen, ipcMain, Tray } = require('electron')
const path = require('path')

var dev = 1//运行环境
var mainpath = __dirname.replace('\\app.asar', '')//app.asar的根目录路径

var win;

function createWindow() {
    win = new BrowserWindow({
        width: 0,
        height: 0,
        minWidth: 1100,
        autoHideMenuBar: true,
        frame: false,  //要创建无边框窗口
        transparent: true, //设置透明
        type: 'toolbar',  //创建的窗口类型为工具栏窗
        webPreferences: {
            preload: path.join(__dirname, 'preload.js'),
            nodeIntegration: true
        }
    })

    win.setPosition(screen.getPrimaryDisplay().workAreaSize.width + 300, 0)
    win.setResizable(false)
    win.loadURL(dev ? 'file://' + __dirname + '/src/index.html#desk' : 'http://localhost:5500/sub-desk/vue-single-soft/src')
    win.setMenu(null)
    // win.webContents.toggleDevTools()
    win.on('close', () => {
        win = null
    })
    var _fn = () => {
        if (win) {
            win.maximize()
            setTimeout(_fn, 100)
        }
    }
    _fn()
}

app.whenReady().then(() => {
    createWindow()

    app.on('activate', () => {
        if (BrowserWindow.getAllWindows().length === 0) {
            createWindow()
        }
    })

    tray = new Tray(path.join(__dirname, 'favicon.ico'))
    tray.on('click', () => {
        if (!win) {
            createWindow()
        } else {
            win.setAlwaysOnTop(true)
            setTimeout(() => {
                win.setAlwaysOnTop(false)
            })
        }
    })
})

const gotTheLock = app.requestSingleInstanceLock()
if (!gotTheLock) {
    app.quit()
}

app.on('window-all-closed', () => {
    if (process.platform !== 'darwin') {
        app.quit()
    }
})

//绑定事件
ipcMain.on('getmainpath', function (ev, res) {
    ev.sender.send('get_mainpath', { mainpath, dev })
})
ipcMain.on('closewin', () => {
    app.quit()
})